package com.xbh.Book.web;

import com.google.gson.Gson;
import com.xbh.Book.pojo.User;
import com.xbh.Book.service.UserService;
import com.xbh.Book.service.impl.UserServiceImpl;
import com.xbh.Book.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

/**
 * @program: JavaWebExer
 * @description: 用户需要实现的业务，增删改查，通过继承BaseServlet从而简化代码，降低耦合
 * @author: 许宝华
 * @create: 2021-04-22 08:53
 */

public class UserServlet extends BaseServlet {
    private UserService userService=new UserServiceImpl();
    /**
     *
     * @param req
     * @param resp
     * @return 登录
     * @author 许宝华
     * @creed: Talk is cheap,show me the code
     * @date 2021/4/22 11:04
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //检查用户名是否可用
        if(userService.existsUsername(username)){
            //可用
            User loginUser = userService.login(new User(null, username, password, null));

            //请求转发，跳转到登录成功的页面
            if (loginUser==null) {
                //把错误的信息和回显的表单项信息，保存到request域中
                req.setAttribute("msg","用户或密码错误");
                req.setAttribute("username",username);
                //登录失败，返回登录页面
                req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);

            } else {
                req.getSession().setAttribute("user",loginUser);
                //登录成功
                req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req,resp);
            }
        }else{
            //不可用
            System.out.println("用户名不可用，请注册,跳转回登录页面");
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);

        }
    }
    /**
     *
     * @param req
     * @param resp
     * @return 注册
     * @author 许宝华
     * @creed: Talk is cheap,show me the code
     * @date 2021/4/22 11:04
     */
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取session中的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //删除sess中的验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        //获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");
        User user=WebUtils.copyParamToBean(req.getParameterMap(),new User());
        //检查验证码是否正确
        //忽略大小写
        if(token!=null&&token.equalsIgnoreCase(code)){
            //正确
            if(userService.existsUsername(username)){
                //不可用
                req.setAttribute("msg","用户名已存在");
                req.setAttribute("username",username);
                req.setAttribute("email",email);
                System.out.println("用户名"+username+"不可用或已存在");
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);

            }else{
                //可用
                userService.registUser(new User(null,username,password,email));
                //跳转到注册成功的页面
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req,resp);

            }
            //
        }else{
            //不正确，调回注册页面
            //请求转发，回到注册页面
            req.setAttribute("msg","验证码错误");
            req.setAttribute("username",username);
            req.setAttribute("email",email);
            System.out.println("验证码错误"+code);
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
        }
    }
    /**
     * 注销用户
     * @param req
     * @param resp
     * @return 注册
     * @author 许宝华
     * @creed: Talk is cheap,show me the code
     * @date 2021/4/22 11:04
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //1、销毁session中用户登录的信息
        HttpSession session = req.getSession();
        session.invalidate();

        //2、重定向到首页（或登陆页面）
        resp.sendRedirect(req.getContextPath());
    }
    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        boolean existsUsername = userService.existsUsername(username);
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("existsUsername",existsUsername);
        Gson gson=new Gson();
        String json = gson.toJson(resultMap);
        resp.getWriter().write(json);
    }
}
